<template>
  <f7-page @page:beforein="pageBeforeIn">
    <f7-navbar>
      <f7-nav-left>
        <f7-link @click="back">
          <f7-icon icon="icon-back" style="margin-left:15px;"></f7-icon>
        </f7-link>
      </f7-nav-left>
      <f7-nav-title title="草稿上传"></f7-nav-title>
    </f7-navbar>
    <f7-block style="margin-top: 10px;">
      <f7-list
        media-list
        style="margin:0px;"
        v-if="draftProblemList.length > 0"
        v-show="isAllChecked() == false"
      >
        <f7-list-item title="全选" @click="checkAll"></f7-list-item>
      </f7-list>
      <f7-list
        media-list
        style="margin:0px;"
        v-if="draftProblemList.length > 0"
        v-show="isAllChecked() == true"
      >
        <f7-list-item title="取消全选" @click="checkAllCacel"></f7-list-item>
      </f7-list>
      <f7-list media-list style="margin:0px;">
        <f7-list-item
          chevron-center
          checkbox
          v-for="(problem, i) in draftProblemList"
          :key="problem.tid"
          :checked="isChecked(i)"
          :title="problemTitle(problem)"
          :subtitle="problemSubtitle(problem)"
          @click="toggleChecked(i)"
          :text="problemText(problem)"
        >
          <img slot="media" width="80" height="80" :src="problemImage(problem)" />
        </f7-list-item>
      </f7-list>
    </f7-block>
    <f7-fab
      v-if="draftProblemList.length > 0"
      position="left-bottom"
      slot="fixed"
      text="上传"
      color="yellow"
      @click="uploadProblemRegistSql"
    >
      <f7-icon f7="arrow_up"></f7-icon>
    </f7-fab>
  </f7-page>
</template>

<script>
/* import global from "../../../../../webapp/static/js/global.js";
import DateUtil from "../../../../../webapp/static/js/DateUtil.js";
import $ from 'jquery';
import events from 'events';
import store from '../../store/store.js'
import TakePhoto from "../../../../global/components/TakePhoto.vue";
 */
import networkEvent from "@/mixins/networkEvent";
import back from "@/mixins/back.js";
import localeCheck from "@/mixins/localeCheck.js";
import Common from "@/utils/Common.js";
import DateUtil from "@/utils/DateUtil.js";
import FileUtil from "@/utils/FileUtil.js";
import events from "events";
import store from "@/store";
import { getUser, setUser, clearUser } from "@/utils/auth";
import { getStore, setStore, clearStore } from "@/utils/storage";
import { upload, uploadImage } from "@/utils/upload";
import keys from "@/utils/rememberKeys";
import request from "@/utils/request";
import db from "@/utils/db";
import TakePhoto from "@/components/TakePhoto.vue";
import eventBus from "@/utils/eventBus.js";
export default {
  mixins: [networkEvent, back],
  store: store,
  components: {
    TakePhoto
  },
  props: {
    draftProblemList: {
      type: Array
    },
    batchId: {
      type: String
    }
  },
  store: store,
  data: function() {
    return {
      checkLists: [],
      problemSuccess: 0,
      problemFail: 0
    };
  },
  methods: {
    toggleChecked: function(index) {
      var value = null;
      if (this.checkLists[index] == null) {
        value = this.draftProblemList[index].tid;
      }
      this.checkLists.splice(index, 1, value);
    },
    isChecked: function(index) {
      return this.checkLists[index] != null;
    },
    checkAllCacel: function() {
      var newList = [];
      for (var i = 0; i < this.checkLists.length; i++) {
        newList.push(null);
      }
      this.checkLists = newList;
    },
    checkAll: function() {
      var newList = [];
      for (var i = 0; i < this.checkLists.length; i++) {
        var tid = this.draftProblemList[i].tid;
        newList.push(tid);
      }
      this.checkLists = newList;
    },
    isAllChecked: function() {
      for (var i = 0; i < this.checkLists.length; i++) {
        if (this.checkLists[i] == null) {
          return false;
        }
      }
      return true;
    },
    problemTitle: function(problem) {
      var title = "";
      if (problem.problemClassId != null) {
        var problemClass = this.$store.state.global.problemClassMap[
          problem.problemClassId
        ];
        title = problemClass.problem_class_name;
        var parentProblemClassId = problemClass.parent_problem_class_id;
        if (parentProblemClassId != null) {
          title =
            this.$store.state.global.problemClassMap[parentProblemClassId]
              .problem_class_name +
            " - " +
            title;
        }
      }
      return title;
    },
    problemSubtitle: function(problem) {
      var subtitle = "";
      if (problem.problemId != null) {
        subtitle = this.$store.state.global.problemMap[problem.problemId]
          .problem_name;
      }
      return subtitle;
    },
    problemText: function(problem) {
      var text = "";
      if (problem.registDate != null) {
        text +=
          DateUtil.dateToStr("yyyy-MM-dd HH:mm", problem.registDate) + " ";
      }
      if (problem.place != null) {
        text += problem.place;
      }
      return text;
    },
    problemImage: function(problem) {
      if (problem.imageFile && problem.imageFile.length > 0) {
        if (problem.smallImageFile && problem.smallImageFile.length > 0) {
          return problem.smallImageFile[0].url;
        } else {
          return problem.imageFile[0].url;
        }
      } else {
        return "";
      }
    },
    pageBeforeIn: function() {
      // this.isOnline = global.isOnline();
    },
    back: function() {
      var self = this;
      this.$f7.dialog.confirm("", "你确定要退出吗？", function() {
        self.$f7router.back();
      });
    },
    uploadProblemRegistSql: function() {
      var self = this;
      let element = null;
      self.problemSuccess = 0;
      self.problemFail = 0;
      if (self.checkLists.length == 0) {
        self.$f7.dialog.alert("请选择上传的记录！", "");
        return;
      } else {
        this.$f7.dialog.confirm("", "确定提交吗?", function() {
          var finishArray = self.checkLists.map(function(tid) {
            return {
              finish: false,
              success: false
            };
          });
          eventBus.$on("regist-submit-finish", function() {
            var successCount = 0;
            var failCount = 0;
            for (var i = 0; i < finishArray.length; i++) {
              if (finishArray[i].finish) {
                finishArray[i].success ? successCount++ : failCount++;
              } else {
                return;
              }
            }
            self.$f7.preloader.hide();
            self.$f7.dialog.alert("", "有" + successCount + "条记录上传成功" + "，有" + failCount + "条记录上传失败");
            self.$f7router.back();
            eventBus.$emit("load-count");
            eventBus.$emit("load-submit");
          });
          self.checkLists.forEach(function(tid, index) {
            for (var i = 0; i < self.draftProblemList.length; i++) {
              if (self.draftProblemList[i].tid == tid) {
                var problem = self.draftProblemList[i];
                if (problem.problemClassId == null) {
                  self.$f7.dialog.alert("", "请选择检查项!");
                  return;
                }
                var parentProblemClass =
                  self.$store.state.global.problemClassMap[
                    self.$store.state.global.problemClassMap[
                      problem.problemClassId
                    ].parent_problem_class_id
                  ];
                if (parentProblemClass.problem_class_name != "工程亮点") {
                  if (problem.repair == null || problem.repair == "") {
                    self.$f7.dialog.alert("", "请选择整改人!");
                    return;
                  }
                  if (problem.reinspects.length == 0) {
                    self.$f7.dialog.alert("", "请选择复验人!");
                    return;
                  }
                }
                let dialog = self.$f7.dialog.progress("上传图片中", 0);
                dialog.finishCount = 0;
                let data = {
                  batchId: problem.batchId,
                  buildingId: problem.buildingId,
                  unitId: problem.unitId,
                  floorId: problem.floorId,
                  houseId: problem.houseId,
                  place: problem.place,
                  problemClassId: problem.problemClassId,
                  problemId: problem.problemId,
                  registBy: problem.regist,
                  remark: problem.remark,
                  emergencyDegree: problem.emergencyDegree,
                  days: problem.repairDeadline,
                  contractorId: problem.contractorId,
                  repairs: [problem.repair],
                  reinspects: problem.reinspects,
                  ccs: problem.ccs,
                  problemValues: problem.problemValues,
                  photos: []
                };
                let promises = [];
                problem.photos.forEach(photoPath => {
                  let promise = FileUtil.read(photoPath, "image/jpeg")
                    .then(blob => {
                      let splits = photoPath.split("/");
                      let filename = splits[splits.length - 1];
                      return uploadImage(filename, blob);
                    })
                    .then(result => {
                      data.photos.push({ url: result.url });
                      dialog.finishCount++;
                      dialog.setProgress(
                        parseInt(
                          dialog.finishCount / (problem.photos.length + 1)
                        ) * 100
                      );
                      return Promise.resolve();
                    });
                  promises.push(promise);
                });
                Promise.all(promises)
                  .then(() => {
                    return request({
                      url: "/api/checkQualityProblem/add",
                      method: "post",
                      data: data
                    });
                  })
                  .then(data => {
                    element = data.element;
                    let promises = [];
                    let promise = null;

                    promise = db.insert("tb_checkquality_problem", [element]);
                    promises.push(promise);

                    promise = db.insert(
                      "tmp_unprocessed_problem_local_check_unprocessed",
                      [element]
                    );
                    promises.push(promise);

                    promise = request({
                      url:
                        "/api/checkQualityRepair/findByCheckQualityProblemId",
                      method: "get",
                      params: {
                        checkQualityProblemId: element.id
                      }
                    })
                      .then(data => {
                        let elements = data.list;
                        return db.insert("tb_checkquality_repair", elements);
                      })
                      .catch(error => {
                        console.error(error);
                        return Promise.resolve();
                      });
                    promises.push(promise);

                    promise = request({
                      url:
                        "/api/checkQualityReinspect/findByCheckQualityProblemId",
                      method: "get",
                      params: {
                        checkQualityProblemId: element.id
                      }
                    })
                      .then(data => {
                        let elements = data.list;
                        return db.insert("tb_checkquality_reinspect", elements);
                      })
                      .catch(error => {
                        console.error(error);
                        return Promise.resolve();
                      });
                    promises.push(promise);

                    return Promise.all(promises);
                  })
                  .then(() => {
                    dialog.close();
                    self.$f7router.emit("submitedProblem", element.id);
                    if (problem.tid != null) {
                      self.$f7router.emit("deleteDraftProblem", problem.tid);
                    }
                    self.$f7router.back();
                    finishArray[index].finish = true;
                    finishArray[index].success = true;
                  })
                  .catch(error => {
                    dialog.close();
                    self.$f7.dialog.alert(error.detail.msg, "提交问题失败！");
                    console.error(error);
                    finishArray[index].finish = true;
                    eventBus.$emit("regist-submit-finish");
                  });
              }
            }
          });
        });
      }
    }
  },
  created: function() {},
  mounted: function() {
    var self = this;
  },
  beforeDestroy: function() {}
};
</script>

<style scoped>
</style>